#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <poll.h>
#include <sys/stropts.h>

int main(int argc, char* argv[]) {
	
	
printf("-2\n"); 
	int sockfd, connfd;
	struct sockaddr_in server_addr;
	struct sockaddr_in client_addr;
	int len = sizeof(server_addr);

	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
	server_addr.sin_port = htons(4567);

	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	bind(sockfd, (struct sockaddr*)&server_addr, len);
	listen(sockfd,20);
		
	int i = 0, maxi = 0, nready = 0;
	int clilen;
	char buf[100] = {0};
	struct pollfd client[100];
	client[0].fd = sockfd;
	client[0].events = POLLRDNORM;
	for (i=1; i<100; i++)
		client[i].fd = -1;
printf("-1\n");	
	for (; ;) {
		nready = poll(client, maxi+1, -1);
printf("0\n");
		if (client[0].revents & POLLRDNORM) {
			clilen = sizeof(client_addr);
			connfd = accept(sockfd, (struct sockaddr*)&client_addr, &clilen);
			
printf("1\n");
			
			struct sockaddr_in addr;
			getpeername(connfd, (struct sockaddr*)&addr, &len);
			printf("%s:%d\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
			
			for (i=1; i<100; i++) {
				if (client[i].fd < 0) {
					client[i].fd = connfd;
					break;
				}
			}	
			if (i == 100) {
				printf("too many\n");
				return -1;
			}
			
			client[i].events = POLLRDNORM;
			if (i > maxi)
				maxi = i;
				
			if (--nready <= 0)
				continue;
		}
		
		for (i=1; i<=maxi; i++) {
			if ((connfd=client[i].fd) < 0)
				continue;
				
			int n = 0;
			if (client[i].revents & (POLLRDNORM | POLLERR)) {
				printf("3\n");
				if ((n=read(connfd, buf, 100)) < 0) {
					if (errno == ECONNRESET) {
						close(connfd);
						client[i].fd = -1;
					}
					else {
						printf("error: %s\n", strerror(errno));
						return -1;
					}
				}
				else if (n == 0) {					
					close(connfd);
					client[i].fd = -1;
				}
				else {
					buf[n] = '\0';
					printf("read: %s\n", buf);
					write(connfd, buf, strlen(buf));
				}
				
				if (--nready <= 0)
					break;
			}
		}
	}
	
	close(sockfd);
	return 0;
}
